package com.example.housingRentalSystem.controller;


import com.example.housingRentalSystem.security.provider.JwtTokenProvider;
import com.example.housingRentalSystem.service.UserService;
import com.example.housingRentalSystem.utils.ApiResponse;
import com.example.housingRentalSystem.utils.HttpStatus;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;

@RestController
@RequestMapping("/api/upload")
public class FileController {

    @Autowired
    private UserService userService;



    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.upload.avatar-max-size}")
    private long maxFileSize;

    @Value("${file.upload.house-image-max-size}")
    private long houseImageMaxFileSize;

    private static final List<String> ALLOWED_AVATAR_TYPES = Arrays.asList(
            "image/jpeg",
            "image/png",
            "image/webp"
    );


    private String getCurrentUserAccount(HttpServletRequest request) {
        String token = getTokenFromHeader(request);
        if (token == null) {
            return null;
        }
        return jwtTokenProvider.getUsernameFromToken(token);
    }

    private String getTokenFromHeader(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    @PostConstruct
    public void init() {
        logger.info("文件上传路径配置: {}", uploadPath);
        Path avatarUploadDir = Paths.get(uploadPath, "avatar");
        Path houseImagesUploadDir = Paths.get(uploadPath, "house-images");
        try {
            Files.createDirectories(avatarUploadDir);
            logger.info("创建头像存储目录: {}", avatarUploadDir);
            Files.createDirectories(houseImagesUploadDir);
            logger.info("创建房屋图片存储目录: {}", houseImagesUploadDir);
        } catch (IOException e) {
            logger.error("目录创建失败", e);
        }
    }

    @PostMapping("/avatar")
    public ApiResponse<Map<String, Object>> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            HttpServletRequest request) {
        logger.info("收到文件: {} ({} bytes)",
                file.getOriginalFilename(),
                file.getSize());
        try {
            String account = getCurrentUserAccount(request);
            if (account == null) {
                return errorResponse(HttpStatus.UNAUTHORIZED, "未登录或Token无效");
            }

            if (file.isEmpty()) {
                return errorResponse(HttpStatus.BAD_REQUEST, "文件不能为空");
            }

            String contentType = file.getContentType();
            if (!ALLOWED_AVATAR_TYPES.contains(contentType)) {
                return errorResponse(HttpStatus.BAD_REQUEST,
                        "不支持的文件类型，仅支持: " + ALLOWED_AVATAR_TYPES);
            }

            if (file.getSize() > maxFileSize) {
                double maxSizeMB = maxFileSize / 1024.0 / 1024.0;
                String errorMsg = String.format("文件大小不能超过 %.1fMB", maxSizeMB);
                return errorResponse(HttpStatus.BAD_REQUEST, errorMsg);
            }

            String originalFilename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFilename);
            String newFilename = UUID.randomUUID().toString().replace("-", "") + "." + extension;

            Path targetPath = Paths.get(uploadPath, "avatar", newFilename);
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

            String avatarPath = "/uploads/avatar/" + newFilename;
            if (avatarPath.length() > 255) {
                throw new IllegalArgumentException("头像路径长度超过数据库限制");
            }

            userService.updateAvatar(account, avatarPath);
            logger.info("用户 {} 头像已更新: {}", account, avatarPath);

            Map<String, Object> responseData = new HashMap<>();
            responseData.put("avatar", avatarPath);
            responseData.put("originalName", originalFilename);
            responseData.put("fileSize", file.getSize());
            responseData.put("contentType", contentType);

            return ApiResponse.success(responseData);

        } catch (IOException e) {
            logger.error("文件存储失败: {}", e.getMessage(), e);
            return errorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "文件处理失败，请稍后重试");
        } catch (IllegalArgumentException e) {
            return errorResponse(HttpStatus.BAD_REQUEST, e.getMessage());
        } catch (Exception e) {
            logger.error("未知错误: {}", e.getMessage(), e);
            return errorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "系统错误");
        }
    }



    private ApiResponse<Map<String, Object>> errorResponse(HttpStatus status, String message) {
        Map<String, Object> errorData = new HashMap<>();
        errorData.put("error", message);
        return new ApiResponse<>(status.getCode(), message, errorData);
    }
}



